﻿<template>
  <a-card :bordered="false" :style="{height: getCardHeight,overflow: 'auto'}">
    <div class="table-operator">
      <a-button
        v-if="hasPerm('Model_DictionaryMain.Add')"
        icon="plus"
        type="primary"
        @click="handleAdd()"
      >新建
      </a-button>
      <a-button
        v-if="hasPerm('Model_DictionaryMain.Delete')"
        :disabled="!hasSelected()"
        :loading="loading"
        icon="minus"
        type="primary"
        @click="handleDelete(selectedRowKeys)"
      >删除
      </a-button>
      <a-button icon="redo" type="primary" @click="handleRefreshPage()">刷新</a-button>
    </div>
    <a-row :gutter="20">
      <a-col span="4">
        <a-directory-tree
          v-if="isShowTree"
          :blockNode="true"
          :load-data="onLoadData"
          :tree-data="treeData"
          defaultExpandAll
          expandAction="dblclick"
          @select="onSelect"
          :style="{ height: getTreeListHeight,overflow: 'auto' }"
        />
      </a-col>
      <a-col span="20">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="10">
              <a-col :md="4" :sm="24">
                <a-form-item label="查询类别">
                  <a-select v-model="queryParam[0].condition">
                    <a-select-option key="DicName">字典名称</a-select-option>
                    <a-select-option key="DicKey">字典Key</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item>
                  <a-input v-model="queryParam[0].keyword" allowClear placeholder="关键字" @keydown="inputKeyDown" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-button type="primary" @click="() => {this.pagination.current = 1; this.getDataList()}">查询</a-button>
                <a-button style="margin-left: 8px" @click="handleRefreshPage">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <a-table
          ref="table"
          :bordered="true"
          :columns="columns"
          :dataSource="data"
          :loading="loading"
          :pagination="pagination"
          :rowKey="(row, index) => row.Id"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'checkbox' }"
          :scroll="{ y: tableHeight }"
          size="small"
          @change="handleTableChange">
          <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime, 'YYYY-MM-DD HH:mm') }}</span>
          <span slot="ModifyDate" slot-scope="ModifyDate">{{ timeFormat(ModifyDate, 'YYYY-MM-DD HH:mm') }}</span>
          <span slot="DicType" slot-scope="DicType">{{ getDicName(DicType) }}</span>
          <span slot="DictionarySubsetsCount" slot-scope="DictionarySubsetsCount">
            <a-tag color="orange" style="width: 100%;font-weight: bold">{{ DictionarySubsetsCount }}</a-tag>
          </span>
          <span slot="DictionaryDetailsCount" slot-scope="DictionaryDetailsCount">
            <a-tag color="blue" style="width: 100%;font-weight: bold">{{ DictionaryDetailsCount }}</a-tag>
          </span>
          <span slot="Enable" slot-scope="Enable">
            <a-tag v-if="Enable == 0" color="red">否</a-tag>
            <a-tag v-else-if="Enable == 1" color="green">是</a-tag>
            <a-tag v-else color="blue">否</a-tag>
          </span>
          <span slot="IsSystem" slot-scope="IsSystem">
            <a-tag v-if="IsSystem == 0" color="red">否</a-tag>
            <a-tag v-else-if="IsSystem == 1" color="green">是</a-tag>
            <a-tag v-else color="blue">否</a-tag>
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a v-if="hasPerm('Model_DictionaryMain.Edit')" @click="handleEdit(record.Id)">编辑</a>
              <a-divider
                v-if="hasPerm('Model_DictionaryMain.Edit') && hasPerm('Model_DictionaryMain.Delete') && record.IsSystem == 0"
                type="vertical" />
              <a v-if="hasPerm('Model_DictionaryMain.Delete') && record.IsSystem == 0" @click="handleDelete([record.Id])">删除</a>
            </template>
          </span>
        </a-table>
      </a-col>
    </a-row>
    <edit-form ref="editForm" :parentObj="this" @returnMain="handleReturnMain"></edit-form>
  </a-card>
</template>

<script>
import EditForm from './EditForm'

const columns = [
  { title: '排序', dataIndex: 'Sort', width: '4%', align: 'center' },
  { title: '字典名称', dataIndex: 'DicName', align: 'left' },
  { title: '字典Key值', dataIndex: 'DicKey', align: 'left' },
  { title: '类型', dataIndex: 'DicType', width: '8%', align: 'center', scopedSlots: { customRender: 'DicType' } },
  { title: '子项', dataIndex: 'DictionarySubsetsCount', width: '5%', align: 'center', scopedSlots: { customRender: 'DictionarySubsetsCount' } },
  { title: '明细', dataIndex: 'DictionaryDetailsCount', width: '5%', align: 'center', scopedSlots: { customRender: 'DictionaryDetailsCount' } },
  { title: '启用', dataIndex: 'Enable', width: '4%', align: 'center', scopedSlots: { customRender: 'Enable' } },
  { title: '系统', dataIndex: 'IsSystem', width: '4%', align: 'center', scopedSlots: { customRender: 'IsSystem' } },
  // {
  //   title: '创建时间',
  //   dataIndex: 'CreateTime',
  //   align: 'center',
  //   width: '8%',
  //   scopedSlots: { customRender: 'CreateTime' }
  // },
  {
    title: '最后修改时间',
    dataIndex: 'ModifyDate',
    align: 'center',
    width: '10%',
    scopedSlots: { customRender: 'ModifyDate' }
  },
  { title: '修改人', dataIndex: 'Modifier', width: '7%', align: 'center' },
  { title: '备注', dataIndex: 'Remark', width: '10%', ellipsis: true },
  { title: '操作', dataIndex: 'action', width: '7%', align: 'left', scopedSlots: { customRender: 'action' } }
]

export default {
  components: {
    EditForm
  },
  created () {
    this.getDicType()
  },
  computed: {
    // 文件区高度
    getCardHeight: function () {
      return (this.tableHeight + 250) + 'px' // 自定义高度需求
    },
    getTreeListHeight: function () {
      return (this.tableHeight + 150) + 'px' // 树形高度
    }
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHeight = this.getTableHeight(true) + 24.5
    })
  },
  data () {
    return {
      tableHeight: 570, // 表格高度
      disabled: false,
      data: [],
      DicList: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'Id', order: 'asc' },
      loading: false,
      columns,
      queryParam: [{ condition: 'DicName', keyword: '' }, { condition: 'ParentId', keyword: '0' }],
      selectedRows: [],
      selectedRowKeys: [],
      treeData: [
        { title: '全部', key: '0' }
      ],
      isShowTree: true
    }
  },
  methods: {
    handleTableChange (pagination, filters, sorter) {
      this.filters = { ...filters }
      this.pagination = { ...pagination }
      this.sorter = { ...sorter }
      this.getDataList()
    },
    handleRefreshPage () {
      this.pagination.current = 1
      this.pagination.pageSize = 25
      this.queryParam = [{ condition: 'DicName', keyword: '' }, { condition: 'ParentId', keyword: '0' }]
      this.treeData = [{ title: '全部', key: '0' }]
      this.isShowTree = false
      setTimeout(() => { this.isShowTree = true }, 10)
    },
    getDataList () {
      this.selectedRowKeys = []
      this.loading = true
      this.$http.post('/Base_BasicData/Model_DictionaryMain/GetDataListByMoreCondition', {
        PageIndex: this.pagination.current,
        PageRows: this.pagination.pageSize,
        SortField: this.sorter.field || 'Id',
        SortType: this.sorter.order,
        Search: this.queryParam,
        ...this.filters
      }).then(resJson => {
        this.loading = false
        this.data = resJson.Data
        if (this.data) {
          const pagination = { ...this.pagination }
          pagination.total = resJson.Total
          this.pagination = pagination
        }
      })
    },
    inputKeyDown (e) {
      if (e.keyCode === 13) {
        if (!this.queryParam[0].keyword) return this.$message.error('请输入查询条件')
        this.getDataList()
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleAdd () {
      this.$refs.editForm.openForm(null, '新建字典信息')
    },
    handleEdit (id) {
      this.$refs.editForm.openForm(id, '编辑字典信息')
    },
    handleDelete (ids) {
      const thisObj = this
      this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return new Promise((resolve, reject) => {
            thisObj.$http.post('/Base_BasicData/Model_DictionaryMain/DeleteData', ids).then(resJson => {
              resolve()
              if (resJson.Success) {
                thisObj.$message.success('操作成功!')
                thisObj.getDataList()
              } else {
                if (resJson.Msg && resJson.Msg.includes('|')) {
                  const Msg = resJson.Msg.split('|')
                  Msg.forEach(item => {
                    thisObj.$message.error(item)
                  })
                } else {
                  thisObj.$message.error(resJson.Msg)
                }
                thisObj.getDataList()
              }
            })
          }),
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
    },
    handleReturnMain () {
      this.handleRefreshPage()
    },
    // 获取字典类型
    getDicType () {
      this.$http.post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
        Condition: 'DicKey',
        Keyword: 'ModelDicType'
      }).then(res => {
        if (res.Success) {
          this.DicList = res.Data.DictionaryDetailsList
        }
      })
    },
    getDicName (DicType) {
      const data = this.DicList.filter(function (item) {
        return item.DicValue === DicType
      })
      if (data.length > 0) {
        return data[0].DicName
      } else {
        return '类型错误'
      }
    },
    // 树形菜单选择
    onSelect (selectedKeys, { node }) {
      this.GetTreeNodeListInfo(node.eventKey)
    },
    // 加载树形数据
    onLoadData (treeNode) {
      const _this = this
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        setTimeout(() => {
          this.$http.post('/Base_BasicData/Model_DictionaryMain/GetDictionaryMainTreeNodeListInfo?parentId=' + treeNode.eventKey).then(resJson => {
            if (resJson.Success) {
              if (resJson.Data && resJson.Data.length > 0) {
                treeNode.dataRef.children = resJson.Data
                _this.treeData = [..._this.treeData]
              }
              _this.GetTreeNodeListInfo(treeNode.eventKey)
            } else {
              _this.$message.error(resJson.Msg)
            }
          })
          resolve()
        }, 100)
      })
    },
    // 根据传入参数获取树形节点信息
    GetTreeNodeListInfo (parentId) {
      this.queryParam[1].keyword = parentId
      this.getDataList()
    }
  }
}
</script>
